<!-- 通用批量导入组件 -->
<template>
  <div class="dialog-file-upload-wrap" :v-has="props.permission">
    <px-upload
      style="margin-right: 8px"
      :action="props.url"
      name="file"
      :headers="headers"
      :on-success="uploadSuccess"
      :on-error="uploadError"
      :show-file-list="false"
    >
      <px-button type="primary" plain>{{ props.title }}</px-button>
    </px-upload>
  </div>
</template>
<script setup lang="ts">
import { reactive, toRefs } from "vue";
import { PxMessage } from "px-ui";
import { getToken } from "@/utils/auth";

// 调用父级-跟新批量上传后的页面
const emits = defineEmits(["updateUploadPage"]);
// 父级传过来的值
const props = defineProps({
  // 文档上传类型add：新增，edit：编辑，view：查看
  url: {
    type: String,
    default: "add",
    required: true
  },
  // 文档上传接口url
  permission: {
    type: String,
    default: "",
    required: true
  },
  // 文档上传接口数据
  title: {
    type: String,
    default: "批量导入",
    required: false
  }
});

const state = reactive<any>({
  headers: {
    Authorization: "Bearer " + getToken().accessToken || ""
  }
});
const { headers } = toRefs(state);
// 批量导入成功状态
const uploadSuccess = response => {
  if (response.success) {
    PxMessage.success("批量导入成功");
    emits("updateUploadPage", response.data);
  } else {
    // 后台返回上传失败信息
    PxMessage.error(response.msg);
  }
};
// 批量导入失败状态
const uploadError = error => {
  // 此处由于后端未处理，前端先统一写"批量导入失败，请重试"
  PxMessage.error("批量导入失败，请重试");
};
</script>
